package thread.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写互斥
 *
 * @author lwmzzz
 * @version 1.0
 * @date 2021/5/16 19:17
 */
public class Test05 {

    public static void main(String[] args) {
        Service service = new Service();
        for (int i = 0; i < 10; i++) {
            new Thread(service::read).start();
        }
        new Thread(service::write).start();
    }

    static class Service {
        ReadWriteLock readWriteLock = new ReentrantReadWriteLock();//定义读写锁

        public void write() {
            try {
                readWriteLock.writeLock().lock();//申请写锁
                System.out.println(Thread.currentThread().getName() + "获得写锁，开始修改数据的数据的时间--" + System.currentTimeMillis());
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "读取数据完毕的时间--" + System.currentTimeMillis());
                readWriteLock.writeLock().unlock();
            }
        }

        public void read() {
            try {
                readWriteLock.readLock().lock();//申请读锁
                System.out.println(Thread.currentThread().getName() + "获得读锁" + System.currentTimeMillis());

                TimeUnit.SECONDS.sleep(3);//睡3秒模拟读操作
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放读锁" + System.currentTimeMillis());
                readWriteLock.readLock().unlock();
            }
        }
    }
}
